import { nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import initRouter from '/@/router/index'
import pinia from '/@/stores/index'
import { useThemeConfig } from '/@/stores/theme-config'
import { Local } from '/@/utils/storage'
import { verifyUrl } from './tools-validate'

/**
 * 设置浏览器标题国际化
 * @function const title = useTitle(); ==> title()
 */
export async function useTitle() {
  const router = await initRouter()
  const stores = useThemeConfig(pinia)
  const { themeConfig } = storeToRefs(stores)
  nextTick(() => {
    let webTitle = ''
    const { globalTitle } = themeConfig.value
    const { path, meta } = router.currentRoute.value
    webTitle = path === '/login' ? <string>meta.title : setTagsViewNameI18n(router.currentRoute.value)
    document.title = webTitle ? `${webTitle} - ${globalTitle}` : globalTitle
  })
}

/**
 * 设置 自定义 tagsView 名称、 自定义 tagsView 名称国际化
 * @param item 路由 query、params 中的 tagsViewName
 * @returns 返回当前 tagsViewName 名称
 */
export function setTagsViewNameI18n(item: any) {
  const { query, params, meta } = item
  return query?.tagsViewName || params?.tagsViewName || meta.title
}

/**
 * 图片懒加载
 * @param element dom 目标元素
 * @param arr 列表数据
 * @description data-xxx 属性用于存储页面或应用程序的私有自定义数据
 */
export const lazyImg = (element: string, arr: EmptyArrayType) => {
  const io = new IntersectionObserver((res: any) => {
    for (const entry of res) {
      if (entry.isIntersecting) {
        const { img, key } = entry.target.dataset
        entry.target.src = img
        entry.target.addEventListener('load', () => {
          io.unobserve(entry.target)
          arr[key].loading = false
        })
      }
    }
  })
  nextTick(() => {
    for (const img of document.querySelectorAll(element)) {
      io.observe(img)
    }
  })
}

/**
 * 全局组件大小
 * @returns 返回 `window.localStorage` 中读取的缓存值 `globalComponentSize`
 */
export const globalComponentSize = (): string => {
  const stores = useThemeConfig(pinia)
  const { themeConfig } = storeToRefs(stores)
  return (
    (themeConfig.value.isComponentSize &&
      Local.get('themeConfig')?.globalComponentSize) ||
      themeConfig.value?.globalComponentSize
  )
}

/**
 * 对象深克隆
 * @param object 源对象
 * @returns 克隆后的对象
 */
export function deepClone(object: EmptyObjectType) {
  let clonedObject: EmptyObjectType
  try {
    clonedObject = object.push ? [] : {}
  } catch {
    clonedObject = {}
  }
  for (const attribute in object) {
    clonedObject[attribute] = object[attribute] && typeof object[attribute] === 'object' ? deepClone(object[attribute]) : object[attribute]
  }
  return clonedObject
}

/**
 * @description 判断是否是移动端
 * @returns {boolean} 返回布尔值
 */
export function isMobile() {
  return /('phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone')/i.test(
    navigator.userAgent
  )
}

/**
 * 判断数组对象中所有属性是否为空，为空则删除当前行对象
 * @description @感谢大黄
 * @param list 数组对象
 * @returns 删除空值后的数组对象
 */
export function handleEmpty(list: EmptyArrayType) {
  const arr = []
  for (const index in list) {
    const d = []
    for (const innerIndex in list[index]) {
      d.push(list[index][innerIndex])
    }
    const leng = d.filter(item => item === '').length
    if (leng !== d.length) {
      arr.push(list[index])
    }
  }
  return arr
}

/**
 * 打开外部链接
 * @param value 当前点击项菜单
 */
export async function openLink(value: RouteItem) {
  const router = await initRouter()
  const { origin, pathname } = window.location

  router.push(value.path)
  const link = value.meta?.isLink
  if (typeof link === 'string' && verifyUrl(link)) {
    window.open(link)
  } else if (typeof link === 'string') {
    window.open(`${origin}${pathname}#${link}`)
  }
}

/**
 * 统一批量导出
 * @function useTitle 设置浏览器标题国际化
 * @function setTagsViewNameI18n 设置 自定义 tagsView 名称、 自定义 tagsView 名称国际化
 * @function lazyImg 图片懒加载
 * @function globalComponentSize() element plus 全局组件大小
 * @function deepClone 对象深克隆
 * @function isMobile 判断是否是移动端
 * @function handleEmpty 判断数组对象中所有属性是否为空，为空则删除当前行对象
 */
const other = {
  useTitle,
  setTagsViewNameI18n(route: RouteToFrom) {
    return setTagsViewNameI18n(route)
  },
  lazyImg: (element: string, arr: EmptyArrayType) => {
    lazyImg(element, arr)
  },
  globalComponentSize: () => {
    return globalComponentSize()
  },
  deepClone: (object: EmptyObjectType) => {
    return deepClone(object)
  },
  isMobile: () => {
    return isMobile()
  },
  handleEmpty: (list: EmptyArrayType) => {
    return handleEmpty(list)
  }
}

// 统一批量导出
export default other
